//
//  TouchButton.swift
//  MySwiftTool
//
//  Created by Chris on 2021/4/16.
//

import UIKit

protocol TouchButtonPositionDelegate: NSObjectProtocol {
    func positionCallBack(position: CGPoint)
    func touchesEnded(sender: TouchButton)
    func startListenScrollView()
}

class TouchButton: UIButton {

    public var delegate: TouchButtonPositionDelegate?

    override var isSelected: Bool {
        didSet {
            super.isSelected = self.isSelected
//            UIView.animate(withDuration: 0.5) {
//                if self.isSelected {
//                    self.alpha = 1
//                } else {
//                    self.alpha = 0
//                }
//            } completion: { (retult) in
//                if retult {
//                    super.isSelected = self.isSelected
//                }
//            }

        }
    }


    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch:AnyObject in touches {
            let t:UITouch = touch as! UITouch
            let gess = t.gestureRecognizers!
            for g:UIGestureRecognizer in gess {
                //防止scrollView滑动时误触
                if !g.isKind(of: UITapGestureRecognizer.self) && gess.count == 1 {
                    delegate?.startListenScrollView()
                    isSelected = true
                }
            }
        }
    }
    open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch:AnyObject in touches {
            let t:UITouch = touch as! UITouch
            let point = t.location(in: self.superview)
            delegate?.positionCallBack(position: point)
        }

    }

    override func touchesEstimatedPropertiesUpdated(_ touches: Set<UITouch>) {

    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        delegate?.touchesEnded(sender: self)
    }

}
